<template>
  <div style="
  position: absolute;
                left:0;
                top:0;
                right:0;
                bottom:0;
                margin:auto;
                height:100%;
                width:370px;
">
    <div>
      <div style="width: 100%;height: 100px;margin-top: 5px">
        <div style="width: 100%;height: 25%">
          <img src="./static/images/力合新图表.jpg" style="width: 100px;height: 100px;margin-top: 15px;
            float: left;border-radius: 50%;
            margin-left: 15px;box-shadow: 0 0 10px burlywood; /* 发光效果 */">
        </div>
        <div style="width: 100%;height: 25%">
          <span style="font-weight: bold;margin-left: 15px;font-size: 17px;float: left;border-radius: 50%;">2024年长护(上海)居家照护培训 </span>
        </div>
        <div style="width: 100%;height: 25%">
            <span
              style="float: left;margin-left: 15px;font-weight: bold;font-size: 14px;margin-top: 5px;color: #7e8c8d">创客老师：{{
                this.name
              }}</span>
        </div>
        <div style="width: 100%;height: 25%">
            <span
              style="float: left;margin-left: 15px;font-weight: bold;font-size: 14px;margin-top: 5px;color: #7e8c8d">老师电话：{{this.type}}</span>
        </div>
        <div style="width: 100%;height: 25%">
            <span
              style="float: left;margin-left: 15px;font-weight: bold;font-size: 14px;margin-top: 5px;color: #7e8c8d">创客编号：{{
                this.id
              }}</span>
        </div>
        <br>
        <hr>
      </div>
    </div>
    <!--    报名信息-->
    <div class="centered-div" style="width: 350px;height: 60%;position: relative;top: 20px;left: 5px;float: left;">
      <h1>填写报名信息</h1>
      <el-form ref="form" :model="form" required :rules="rules" label-width="80px" style="margin-top: 30px">
<!--        <el-form-item label="报名类型" required prop="bmtype" style="float: left">-->
<!--          <el-select style="width: 240px" v-model="form.bmtype" placeholder="请选择报名类型">-->
<!--            <el-option label="上海户籍" value="1790"></el-option>-->
<!--            <el-option label="非上海户籍" value="1990"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item required prop="bmName" label="学员姓名" style="float: left;">
          <el-input placeholder="请输入姓名" style="width: 240px" v-model="form.bmName"></el-input>
        </el-form-item>

        <el-form-item style="float: left;" required prop="bmTel" label="学员电话">
          <div style="width: 100%;height: 40px;">
            <el-input placeholder="请输入手机号码" v-model="form.bmTel" style="float: left;width: 240px"></el-input>
          </div>
        </el-form-item>
        <el-form-item style="float: left" required prop="bmUID" label="证件编号">
          <!--            <el-input placeholder="请输入身份证编号" style="width: 240px" v-model="form.bmUID" @change="idCard(form.bmUID)"></el-input>-->
          <el-input placeholder="请输入身份证编号" style="width: 240px" v-model="form.bmUID"></el-input>
        </el-form-item>
        <el-button type="primary" @click="onSubmit"
                   style="width:100%;background-color: burlywood;border:none;margin-top: 20px">提交订单
        </el-button>
      </el-form>
    </div>
  </div>

</template>
<script>
import {WxPay} from '@/api/WeiXin.js'
import wx from 'weixin-js-sdk'
import {Base64} from "js-base64";

export default {
  data() {
    return {
      form: {
        bmName: '',
        bmTel: '',
        bmUIDType: 1,
        bmUID: '',
        bmSex: 1,
        bmdateBirth: '',
        bmtype: '1990',
        bmid: '', //创客老师id
        lsname: '', //创客老师名称
        openid: '', //学员缴费的微信openid
      },
      rules: {
        bmtype: [{required: true, message: '请选择报名类型', trigger: 'blur'}],
        bmName: [{required: true, message: '请输入姓名', trigger: 'blur'}],
        bmTel: [{required: true, message: '请输入电话', trigger: 'blur'}],
        bmUIDType: [{required: true, message: '请输入证件类型', trigger: 'blur'}],
        bmUID: [{required: true, message: '请输入证件编号', trigger: 'blur'}],
        bmSex: [{required: true, message: '请输入性别', trigger: 'blur'}],
        bmdateBirth: [{required: true, message: '请输入出生年月', trigger: 'blur'}],
      },
      id: '',
      name: '',
      openid: '',
      type: '',
    };
  },
  methods: {
    //身份证校验
    // idCard(idCard) {
    //   if (this.form.bmUIDType === 1) {
    //     // 根据身份证号获取日期
    //     const dateObj = new Date(idCard.substring(6, 14).replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')) // 将字符串转换为日期对象
    //     this.form.bmdateBirth = dateObj
    //     // 根据身份证号判断性别（奇数为男性，偶数为女性）
    //     this.form.bmSex = idCard.charAt(16) % 2 === 0 ? 2 : 1
    //   }
    // },
    //提交
    onSubmit() {
      this.$refs.form.validate(valid => {
        //在提交表单时执行验证逻辑
        if (valid) {
          if (this.form.bmUIDType === 1) {
            // 判断证件类型是否为身份证
            if (!/^\d{17}(\d|X|x)$/.test(this.form.bmUID)) { // eslint-disable-line
              this.$message.warning('请输入有效的身份证号码')
              return
            }
            // 校验最后一位的校验码
            let weightFactor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
            let checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
            let sum = 0
            for (let i = 0; i < 17; i++) {
              sum += parseInt(this.form.bmUID.charAt(i)) * weightFactor[i]
            }
            let index = sum % 11
            if (checkCode[index] !== this.form.bmUID.charAt(17)) {
              this.$message.warning('请输入正确的身份证号码，校验码错误')
              return
            }
            // 校验出生日期
            const dateObj = new Date(this.form.bmUID.substring(6, 14).replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')) // 将字符串转换为日期对象
            this.form.bmdateBirth = dateObj
            let birthDateRegex = /(\d{4})(\d{2})(\d{2})/
            let birthDateMatch = birthDateRegex.exec(this.form.bmUID.substring(6, 14))
            if (!birthDateMatch) {
              this.$message.warning('请输入正确的身份证号码，出生日期格式错误')
              return
            }
            // 根据身份证号判断性别（奇数为男性，偶数为女性）
            this.form.bmSex = this.form.bmUID.charAt(16) % 2 === 0 ? 2 : 1
          }
          if (this.form.bmTel.length !== 11) {
            this.$message.warning('手机号码必须为11位！')
            return
          }
          if (this.form.bmName.length > 5) {
            this.$message.warning('姓名错误！')
            return
          }
          /**
           * 全部的表单验证通过、这里调用微信支付的接口
           */
          if (this.form.bmSex === 1) {
            this.form.bmSex = '男'
          } else {
            this.form.bmSex = '女'
          }
          if (this.form.bmUIDType === 1) {
            this.form.bmUIDType = '身份证'
          }
          if (this.form.bmUIDType === 2) {
            this.form.bmUIDType = '护照'
          }
          if (this.form.bmUIDType === 3) {
            this.form.bmUIDType = '其他'
          }
          this.form.bmid = this.id
          this.form.lsname = this.name
          this.form.openid = this.openid
          // console.log(this.form)
          /**
           *  调用后端微信接口预支付并拿到pay_id等参数,前端使用pay_id调用微信支付
           */
          var that =this;
          // let subData = 'openid=' + this.openid + '&type=' + this.form.bmtype
          WxPay(this.form).then(res => {
            console.log(res.data)
            wx.config({
              debug: false, // 这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
              appId: res.data.appId, // 必填，公众号的唯一标识
              timestamp: res.data.timeStamp, // 必填，生成签名的时间戳
              nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
              signature: res.data.paySign, // 必填，签名
              jsApiList: ['chooseWXPay', 'checkJsApi'] // 必填，需要使用的JS接口列表
            })
            wx.ready(() => {
              // wx.checkJsApi({
              //   jsApiList: ['chooseWXPay'],
              //   success:function(res){},
              //   fail:function(res){}})
              wx.chooseWXPay({
                timestamp: res.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位
                package: 'prepay_id=' + res.data.prepayId, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: 'RSA', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: res.data.paySign, // 支付签名
                success: function (payRes) {
                  that.showAccomplish(that.form.bmName,that.form.bmUID,that.form.bmTel)
                  that.$message.success('支付成功')
                },
                cancel: function (payRes) {
                  that.$message.error('取消支付')
                },
                fail: function (payRes) {
                  that.$message.error('支付失败')
                }
              })
            })
          })
        } else {
          // 表单验证不通过，提示错误信息
          this.$message.error('请填写必填项')
        }
      })
    },
    //页面跳转
    showAccomplish(name,IDcard,phone) {
      // 使用 $router.push() 方法进行页面跳转，并携带参数
      this.$router.push({
        name: 'accomplish',
        params: {
          name:name,
          phone:phone,
          IDcard:IDcard
        }
      })
    },
  },
  created() {
    // 接收二维码传过来的参数值
    function getParameterByName(name) {
      name = name.replace(/[\[\]]/g, '\\$&') // eslint-disable-line
      var url = window.location.href
      var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
      var results = regex.exec(url)
      if (!results) return null
      if (!results[2]) return ''
      // 解码中文字符
      return decodeURIComponent(results[2].replace(/\+/g, ' '))
    }
    this.name = Base64.decode(getParameterByName("name"));
    this.id = getParameterByName("id");
    this.openid = getParameterByName("openid");
    this.type = getParameterByName("type"); //电话
    // alert(this.name)
    // alert(this.id)
    // alert(this.openid)
    // console.log(this.name)
    // console.log(this.id)
    // console.log(this.openid)
    // console.log(this.type)
    // this.openid = "o3FTe6dBzidn4Qihh8kIC-ht3ggs"
    // this.form.bmtype = "1990"

  }
};
</script>
<style scoped>

</style>
